/*************************************************
 * ThinkJot V2
 * Author: Jeswin P. (jeswin@process64.com)
 * Website: http://www.process64.com/thinkjot/
 * This code is distributed under the terms of the
 * Apache License, Version 2.0.
 * **********************************************/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

using ThinkJot.Core.Utils;
using ThinkJot.Core.Blogs;
using ThinkJot.Core.Configuration;

public partial class Blogs_EditEntryControl : BlogControlBase
{
    private const int Action_Publish = 1;
    private const int Action_SaveDraft = 2;
    private const int Action_SaveAsArticle = 3;
    private const int Action_CancelEdit = 4;

    private string contentText = "";
    private string dateText = "";
    
    private EditModes editMode;
    public EditModes EditMode
    {
        get { return editMode; }
        set { editMode = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (editMode == EditModes.New)
            {
                InitCreateEntryMode();
            }
            if (editMode == EditModes.Update)
            {
                InitEditEntryMode();
            }
        }
    }

    protected void saveEntryButton_Click(object sender, EventArgs e)
    {
        SaveEntry(true, BlogEntry.NormalType, Action_Publish);      
    }

    protected void cancelButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("default.aspx");
    }

    protected string GetEntryMode()
    {
        if (editMode == EditModes.New) return "New Post";
        if (editMode == EditModes.Update) return "Update Post";
        return "";
    }

    private void LoadCurrentValues(BlogEntry entry)
    {
        ViewState["entryId"] = entry.UniqueId;
        titleTextBox.Text = entry.Title;
        descriptionTextBox.Text = entry.Description;
        contentText = entry.Content;
        allowCommentsCheckBox.Checked = entry.AllowComments;
        syndicateCheckBox.Checked = entry.Syndicate;
        excludeFromListCheckBox.Checked = entry.ExcludeFromList;

        //date stuff, utc blah blah
        DateTime displayTime;
        if (Config.UseUniversalTime)
            displayTime = entry.Time;
        else
        {
            if (Config.UseServerLocalTime)
                displayTime = entry.Time.ToLocalTime();
            else
                displayTime = DateTimeUtility.AddTimeOffset(entry.Time, Config.UtcOffset);
        }
        timeTextBox.Text = displayTime.ToLongTimeString();
        dateText = displayTime.ToString("yyyy/MM/dd");
        //date stuff ends here...
        
        disableCommentDaysCheckBox.SelectedValue = entry.DisableCommentsAfterDays.ToString();
        closeComments.Checked = entry.CommentsClosed;

        foreach (int catId in entry.CategoryIds)
        {
            foreach (ListItem item in categoryBoxes.Items)
            {
                if (item.Value == catId.ToString())
                {
                    item.Selected = true;
                    break;
                }
            }
        }

        string strTags = "";
        if (entry.Tags.Count > 0)
            strTags = string.Join(", ", entry.Tags.ToArray());
        tagsTextBox.Text = strTags;
    }

    private void InitEditEntryMode()
    {
        Guid entryId = new Guid((string)Request["entryId"]);
        BlogEntry entry = BlogEntry.GetBlogEntry(entryId, BlogName);
        LoadCategoryCheckBoxes();
        LoadCurrentValues(entry);
    }

    private void InitCreateEntryMode()
    {
        timeTextBox.Visible = false;
        LoadCategoryCheckBoxes();
    }

    private void LoadCategoryCheckBoxes()
    {
        List<Category> cats = Category.GetAllCategories(BlogName);
        categoryBoxes.DataSource = cats;
        categoryBoxes.DataBind();
    }

    protected string GetTinyMCEPath()
    {
        return PathUtility.CombineUrls(SysConfig.ComponentsUrl, "tinymce/jscripts/tiny_mce/tiny_mce.js");
    }

    protected string GetCalendarPopupPath()
    {
        return PathUtility.CombineUrls(SysConfig.ComponentsUrl, "calendarpopup/calendarpopup.js");
    }

    protected string GetJSCalendarEnPath()
    {
        return PathUtility.CombineUrls(SysConfig.ComponentsUrl, "jscalendar/lang/calendar-en.js");
    }

    protected string GetJSCalendarSetupPath()
    {
        return PathUtility.CombineUrls(SysConfig.ComponentsUrl, "jscalendar/calendar-setup.js");
    }

    protected string GetContentText()
    {
        return contentText;
    }

    protected string GetDateText()
    {
        return dateText;
    }

    protected string GetEditIconPath()
    {
        return PathUtility.CombineUrls(SysConfig.ImagesUrl, "Blogs/edit-entry-ico.jpg");
    }
    protected void imageUploadButton_Click(object sender, EventArgs e)
    {
        string savedFileName = "";
        if (imageUpload.PostedFile.ContentLength > 0)
        {
            savedFileName = BlogEntry.SaveFile(imageUpload.FileName, imageUpload.FileBytes, BlogName, false);
        }
        dateText = Request["dateBox"];
        contentText = Request["contentBox"] +
            "<img src=\"" + PathUtility.CombineUrls(PathUtility.GetBlogMediaUrl(BlogName), savedFileName) +
            "\" alt=\"" + altTextTextBox.Text + "\" />";
    }

    protected void fileUploadButton_Click(object sender, EventArgs e)
    {
        if (fileUpload.PostedFile.ContentLength > 0)
        {
            BlogEntry.SaveFile(fileUpload.FileName, fileUpload.FileBytes, BlogName, false);
        }
        dateText = Request["dateBox"];
        contentText = Request["contentBox"];
    }

    protected string GetTimeBoxVisibility()
    {
        if (editMode == EditModes.New) return "false";
        return "true";
    }

    public bool IsNewEntry()
    {
        return editMode == EditModes.New;
    }

    protected void saveDraftButton_Click(object sender, EventArgs e)
    {
        SaveEntry(false, BlogEntry.NormalType, Action_SaveDraft);
    }

    private void SaveEntry(bool publish, int blogEntryType, int action)
    {
        BlogEntry blogEntry = new BlogEntry();
        blogEntry.EntryType = blogEntryType;
        blogEntry.Title = titleTextBox.Text;
        blogEntry.Description = descriptionTextBox.Text;
        blogEntry.Content = Request["contentBox"];
        blogEntry.AllowComments = allowCommentsCheckBox.Checked;
        blogEntry.Syndicate = syndicateCheckBox.Checked;
        blogEntry.ExcludeFromList = excludeFromListCheckBox.Checked;
        blogEntry.CommentsClosed = closeComments.Checked;

        int disableCommentsDays = Convert.ToInt32(disableCommentDaysCheckBox.SelectedValue);
        blogEntry.DisableCommentsAfterDays = disableCommentsDays;

        blogEntry.Publish = publish;
        blogEntry.Author = System.Web.Security.Membership.GetUser().UserName;
        
        //we will change the modified time automatically. 
        if (editMode == EditModes.Update) blogEntry.ModifiedTime = DateTime.Now.ToUniversalTime();

        //user has the option of manually changing the created time.
        //time zone complications come into play.
        if (editMode == EditModes.Update)
        {
            string date = Request["dateBox"];
            DateTime dt = DateTime.MinValue;
            bool isTimeValid = DateTime.TryParse(date + " " + timeTextBox.Text, out dt);
            if (!isTimeValid)
            {
                //We cannot validate Date+Time; 
                //See if we are lucky with just the Date part
                DateTime.TryParse(date, out dt);
            }
            //By now, dt = a valid DateTime if everything succeeded

            if (dt != DateTime.MinValue) //dt contains a valid value!
            {
                //The value in dt depends on blog-config
                if (Config.UseUniversalTime)
                    blogEntry.Time = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
                else
                {
                    if (Config.UseServerLocalTime)
                    {
                        DateTime localTime = DateTime.SpecifyKind(dt, DateTimeKind.Local);
                        blogEntry.Time = localTime.ToUniversalTime();
                    }
                    else
                    {
                        DateTime customTime = DateTimeUtility.SubtractTimeOffset(dt, Config.UtcOffset);
                        blogEntry.Time = DateTime.SpecifyKind(customTime, DateTimeKind.Utc);
                    }
                }
            }
            else //dt was invalid. Let's just put the current UTC in.
            {
                blogEntry.Time = DateTime.Now.ToUniversalTime();
            }
        }
        else
            //New Entry. Give Current Time.
            blogEntry.Time = DateTime.Now.ToUniversalTime();

        foreach (ListItem item in categoryBoxes.Items)
        {
            if (item.Selected) blogEntry.CategoryIds.Add(Convert.ToInt32(item.Value));
        }

        if (!string.IsNullOrEmpty(tagsTextBox.Text))
        {
            string[] tags = tagsTextBox.Text.Split(',');
            List<string> entryTags = new List<string>();
            foreach (string tag in tags)
            {
                if (!string.IsNullOrEmpty(tag))
                {
                    string trimmedTag = tag.Trim();
                    entryTags.Add(trimmedTag);
                }
            }
            if (entryTags.Count > 0)
                blogEntry.Tags = entryTags;
        }

        switch (editMode)
        {
            case EditModes.Update:
                blogEntry.UniqueId = (Guid)ViewState["entryId"];
                blogEntry.Update(BlogName);
                break;
            case EditModes.New:
                blogEntry.Save(BlogName);
                break;
        }
        if (imageUpload.PostedFile.ContentLength > 0)
        {
            BlogEntry.SaveFile(imageUpload.FileName, imageUpload.FileBytes, BlogName, false);
        }

        if (action == Action_Publish || action == Action_SaveAsArticle || action == Action_CancelEdit)
            Response.Redirect(GetMappedBlogUrl());

        if (action == Action_SaveDraft)
            Response.Redirect("adminpage.aspx?function=EditEntry&entryId=" + blogEntry.UniqueId.ToString());
    }

    protected void saveArticleButton_Click(object sender, EventArgs e)
    {
        //There is no draft option for artcles.
        SaveEntry(true, BlogEntry.ArticleType, Action_SaveAsArticle);
    }
}
